mod base_script;
mod js_runtime;

use crate::context::CONTEXT;
use crate::model::version::VersionItem;
use deno_runtime::deno_core::futures::FutureExt;
use deno_runtime::deno_core::serde_json;
use std::fs::read_to_string;
use std::path::PathBuf;

pub type JsValue = serde_json::Value;

pub(crate) struct Plugin {
    name: String,
    channel: String,
    plugin: PathBuf,
    plugin_code: String,
}

impl<'a> Plugin {
    pub(crate) fn new(plugin_name: String, channel: Option<String>) -> Plugin {
        let channel_name = if channel.is_some() {
            format!("-{}", channel.clone().unwrap())
        } else {
            "".parse().unwrap()
        };

        let mut plugin =
            CONTEXT
                .plugin_dir
                .join(format!("{}{}.ts", plugin_name.clone(), channel_name));
        let mut plugin_code: String = String::new();
        if !plugin.exists() {
            plugin = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
                .join("plugin")
                .join("inner")
                .join(format!("{}.ts", plugin_name));
            println!("use inner plugin:{:?}", plugin)
        }
        if !plugin.exists() {
            panic!("inner {} not found {:?}", plugin_name, plugin);
        }
        Self {
            name: plugin_name,
            channel: channel.unwrap_or("".to_string()),
            plugin,
            plugin_code,
        }
    }

    pub(crate) fn versions(&self) -> Vec<VersionItem<'a>> {
        let mut runtime = js_runtime::Script::new(self.plugin_code.clone(), vec![]);
        let result = runtime.run_js();
        result.then(|f| async move {
            println!("{:?}", f)
        });
        vec![]
    }
}
